package com.zhu.storesmanager;

import com.zhu.storesmanager.common.MyLocation;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.location.Location;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.TextView;

/**
 * 签到界面
 */
public class SalespersonSigninActivity extends Activity implements View.OnClickListener{

	private TextView mTitleView = null; //标题栏
	private TextView mTimeView = null; //当前时间
	private TextView mSignStatusView = null; //签到状态
	private View mSiginButton = null;//签到按钮
	private boolean isSignIn = false; //是否签到
	private long mSignInTime = 0; //签到时间
	private Location mResultLocation = null;
	private MyLocation mMyLocation = null; //定位

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_signin); //设置显示界面

		setupView();
		initData();
	}

	/**
	 * 初始化界面
	 */
	private void setupView(){
		mTitleView = (TextView)findViewById(R.id.title_text);
		mTimeView = (TextView)findViewById(R.id.signin_time_view);
		mSiginButton = findViewById(R.id.signin_button);
		mSiginButton.setOnClickListener(this);
		mSignStatusView = (TextView)findViewById(R.id.signin_status_text);
		findViewById(R.id.signin_bottom_back).setOnClickListener(this);
	}

	/**
	 * 初始化数据
	 */
	private void initData(){
		mTitleView.setText(getString(R.string.salesperson_name, DataUtils.mUserData.mRealName));
		getSigninStatus();
		updateView();
	}

	/**
	 * 更新界面
	 */
	private void updateView(){
		if(isSignIn){
			mSignStatusView.setText(getString(R.string.singined, Actions.formatTime(mSignInTime)));
			mSiginButton.setEnabled(false);
		}else{
			mSiginButton.setEnabled(true);
			mSignStatusView.setText(R.string.nosignin);
		}
	}

	/**
	 *生命周期 界面恢复
	 *@see android.app.Activity#onResume()
	 */
	public void onResume(){
		super.onResume();
		mTimeView.setText(Actions.getFormatCurTime());
		registerTimeChange();
	}

	/**
	 * 生命周期 界面暂停 退到后台等
	 * @see android.app.Activity#onPause()
	 */
	public void onPause(){
		super.onPause();
		unregisterReceiver(mReceiver); //移除时间监听
	}

	/**
	 * 点击按钮事件响应
	 * @param arg0 点击的button
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if(arg0 != null){
			switch(arg0.getId()){
				case R.id.signin_bottom_back: //返回
					finish();
					break;
				case R.id.signin_button: //签到
					startSignIn();
					break;
			}
		}
	}

	/**
	 * 注册时间变化广播
	 */
	private void registerTimeChange(){
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_TIME_CHANGED);
		filter.addAction(Intent.ACTION_TIME_TICK);
		filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
		this.registerReceiver(mReceiver, filter); //注册监听时间发生变化
	}

	/**
	 * 时间变化消息接受
	 */
	private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			mTimeView.setText(Actions.getFormatCurTime()); //更新时间
		}
	};

	/**
	 * 获取签到状态
	 */
	private void getSigninStatus(){
		String where = StoresManagerSettings.SignInInfoColumns.SINGIN_TIME + ">0"; //查询数据库条件
		Cursor cursor = getContentResolver().query(StoresManagerSettings.SignInInfoColumns.CONTENT_URI_NO_NOTIFICATION,
				null, where, null, null); //查询
		if(cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()){ //数据存在 则已经签到成功
			isSignIn = true;
			mSignInTime = cursor.getLong(cursor.getColumnIndexOrThrow(StoresManagerSettings.SignInInfoColumns.SINGIN_TIME));
		}
		if(cursor != null){
			cursor.close();
			cursor = null;
		}
	}

	/**
	 * 开始签到
	 */
	private void startSignIn(){
		if(!Actions.isGPSWorking(this)){ //检查GPS
            Actions.alertShowDetails(this, getString(R.string.tips_label),
                    getString(R.string.gps_is_unavailable),
                    R.string.dialog_setting, R.string.dialog_close,
                    new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int arg1) {
                            Actions.openSettingIntent(SalespersonSigninActivity.this,
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        }
                    }, new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int arg1) {

                        }
                    });
            return;
		}
		if(mMyLocation == null){
			mMyLocation = new MyLocation(this, true, false);
		}
		mMyLocation.getLocation(mLocationResult, true);
	}

	/**
	 * 定位结果返回
	 */
	private MyLocation.LocationResult mLocationResult = new MyLocation.LocationResult(){

		@Override
		public void onLocationResult(Location location) {
			// TODO Auto-generated method stub
			mResultLocation = location;
			saveSignInData();
		}
	};

	/**
	 * 保存签到数据
	 */
	private void saveSignInData(){
		isSignIn = true;
		if(mMyLocation != null){
		    mSignInTime = mMyLocation.getCurrentTime();
		}else{
		    mSignInTime = System.currentTimeMillis();
		}
		ContentValues values = new ContentValues();
		values.put(StoresManagerSettings.SignInInfoColumns.SINGIN_TIME, mSignInTime); //签到时间和经纬度数据
		values.put(StoresManagerSettings.SignInInfoColumns.SINGIN_LAT, mResultLocation != null ? mResultLocation.getLatitude() : 0);
		values.put(StoresManagerSettings.SignInInfoColumns.SINGIN_LNG, mResultLocation != null ? mResultLocation.getLongitude() : 0);
		getContentResolver().insert(StoresManagerSettings.SignInInfoColumns.CONTENT_URI_NO_NOTIFICATION, values);
		updateView();
	}
}
